package tag_service

import (
	"encoding/json"
	"gin_blog/models"
	"gin_blog/pkg/gredis"
	"gin_blog/pkg/logging"
	"gin_blog/service/cache_service"
)

type Tag struct {
	ID int
	Name string
	CreatedBy string
	ModifiedBy string
	State int

	PageNum  int
	PageSize int
}

func (t *Tag)Gets()([]*models.Tag,error)  {
	var (
		tags,cacheTags []*models.Tag
	)
	cache :=cache_service.Tag{
		ID:t.ID,
		Name:t.Name,
		State:t.State,

		PageNum:t.PageNum,
		PageSize:t.PageSize,
	}
	key :=cache.GetTagsKey()
	if gredis.Exists(key){
		data,err :=gredis.Get(key)
		if err!=nil{
			logging.Info(err)
		}else {
			json.Unmarshal(data,&cacheTags)
			return cacheTags,nil
		}
	}
	tags,err :=models.GetTags(t.PageNum,t.PageSize,t.getMaps())
	if err!=nil{
		return nil, err
	}
	_, _ = gredis.Set(key, tags, 3600)
	return tags,nil
}
func (t *Tag) Add() error {
	return models.AddTag(t.Name,t.State,t.CreatedBy)
}
func (t *Tag)Edit()error  {
	return models.EditTag(t.ID, map[string]interface{}{
		"id":t.ID,
		"name":t.Name,
		"modified_by":t.ModifiedBy,
		"state":t.State,
	})
}
func (t *Tag)Delete()error  {
	return models.DeleteTag(t.ID)
}
func (t *Tag)ExistByName() (bool,error) {
	return models.ExistTagByName(t.Name)
}
func (t *Tag)ExistByID() (bool,error) {
	return models.ExistTagByID(t.ID)
}
func (t *Tag)Count() (total int, err error) {
	return models.GetTagTotal(t.getMaps())
}

func (t *Tag)getMaps() map[string]interface{} {
	maps :=make(map[string]interface{})
	maps["deleted_on"]=0
	if t.State!=-1{
		maps["state"]=t.State
	}
	if t.Name!=""{
		maps["name"]=t.Name
	}
	return maps
}